# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
bilibili评论 分两种。1.md*** 2.av****
电影
https://www.bilibili.com/bangumi/media/md123092/
id 为md值
游标为每次返回数据提取
https://www.bilibili.com/video/av93932830
"""

class B_Pl():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        self.cookie = cookiejar.CookieJar()
        # ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # "User-Agent": ua.random
            # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Cookie': 'INTVER=1; _uuid=16CC7F1F-3CC7-C1A3-BFEA-4FA0FE27DE9584719infoc; buvid3=7F5E6DAE-5208-4D66-87F8-0C2BBA14560F53948infoc; CURRENT_FNVAL=16; sid=7uxxux7o; LIVE_BUVID=AUTO3915834577633051',
            'DNT': '1',
            'Host': 'api.bilibili.com',
            'Referer': 'https://www.bilibili.com/video/av93690054/?spm_id_from=333.851.b_7265706f7274466972737432.3',
            'Sec-Fetch-Dest': 'script',
            'Sec-Fetch-Mode': 'no-cors',
            'Sec-Fetch-Site': 'same-site',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
        }

    # av开头
    def get_conmments_av(self, id, cursor):
        postData = {
            'callback': 'jQuery17209888475097674703_1583457779214',
            'jsonp': 'jsonp',
            'pn': cursor,
            'type': '1',
            'oid': id,
            'sort': '2',
            '_': int(time.time() * 1000)
        }
        url = f"https://api.bilibili.com/x/v2/reply"
        html = HttpUtils.do_request("GET", url, self.headers, postData)
        data = html.text.replace("jQuery17209888475097674703_1583457779214", "").replace("(", "").replace(")", "")
        data_json = json.loads(data)
        for d in data_json['data']['replies']:
            dict_data = dict()
            dict_data['mid'] = d['member']['mid']  # id
            dict_data['uname'] = d['member']['uname']  # 用户名
            dict_data['uname'] = d['member']['sex']  # 用户名
            dict_data['current_level'] = d['level_info']['current_level']  # 用户级别
            dict_data['content'] = d['content']['message']
            dateArray = datetime.fromtimestamp(d['ctime'])
            dict_data['ctime'] = dateArray.strftime("%Y-%m-%d %H:%M:%S")
            dict_data['like'] = d['like']  # 有用
            print(str(dict_data))


    # md开头
    def get_conmments_md(self, id, cursor):
        url = f"https://api.bilibili.com/pgc/review/short/list?media_id={id}&ps=20&sort=0&cursor={cursor}"
        html = HttpUtils.do_request("GET", url, self.headers, "")
        data_json = json.loads(html.text)
        cursor = data_json['data']['next']  # 游标
        total = data_json['data']['total']  # 总数量
        for d in data_json['data']['list']:
            dict_data = dict()
            dict_data['mid'] = d['author']['mid']  # id
            dict_data['uname'] = d['author']['uname']  # 用户名
            dict_data['content'] = d['content']
            dateArray = datetime.fromtimestamp(d['ctime'])
            dict_data['ctime'] = dateArray.strftime("%Y-%m-%d %H:%M:%S")
            dict_data['score'] = d['score']  # 总分
            dict_data['likes'] = d['stat']['likes']  # 有用
            dict_data['liked'] = d['stat']['liked']  # 无用
            print(str(dict_data))
        self.get_conmments_md(id, cursor)


if __name__ == '__main__':
    pinglun = B_Pl()
    # md
    # pinglun.get_conmments_md("93690054", "0")
    # av
    for i in range(1, 100):
        pinglun.get_conmments_av("93690054", i)